﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NAudio.Wave;

namespace MidiPlayer
{
    public partial class PlaybackSettingsForm : Form
    {
        public PlaybackSettingsDto Settings;

        public PlaybackSettingsForm(PlaybackSettingsDto set)
        {
            Settings = set;

            InitializeComponent();

            InitAsio();

            UpdateView();
            
        }

        private void InitAsio()
        {
            if (!AsioOut.isSupported())
            {
                rbAsio.Enabled = false;
                cbAsioDriver.Enabled = false;
                lblAsioOutput.Enabled = false;

            }
            else
            {
                // Just fill the comboBox AsioDriver with available driver names
                String[] asioDriverNames = AsioOut.GetDriverNames();
                foreach (string driverName in asioDriverNames)
                {
                    cbAsioDriver.Items.Add(driverName);
                }
                cbAsioDriver.SelectedIndex = 0;
            }

        }

        private void UpdateView()
        {
            tbLatency.Text = Settings.Latency.ToString();
   
            if(Settings.Output == PlaybackSettingsDto.Outputs.Asio
                && AsioOut.isSupported())
            {
                rbAsio.Checked = true;
                if(cbAsioDriver.Items.Contains(Settings.AsioDriverName))
                {
                    cbAsioDriver.SelectedItem = Settings.AsioDriverName;
                }
            }
            else
            {
                rbDirectSound.Checked = true;
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            int lat = 0;
            if(int.TryParse(tbLatency.Text, out lat))
            {
                if(lat < 0 || lat > 1000)
                {
                    MessageBox.Show("Enter valid latency (0 to 1000)");
                    tbLatency.Focus();
                    return;
                }
                Settings.Latency = lat;
            }
            else
            {
                MessageBox.Show("Enter valid latency");
                tbLatency.Focus();
                return;
            }

            if(rbDirectSound.Checked)
            {
                Settings.Output = PlaybackSettingsDto.Outputs.DirectSound;
            } else
            {
                Settings.Output = PlaybackSettingsDto.Outputs.Asio;
                Settings.AsioDriverName = cbAsioDriver.SelectedItem.ToString();
            }
            this.Close();
        }
    }
}
